package cn.xiaoke.damowang_boot_test.domain.interfac;

import cn.xiaoke.damowang_boot_test.domain.org.Department;
import cn.xiaoke.damowang_boot_test.domain.org.School;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

//@JSONType(typeKey = "__class",seeAlso = {Department.class,School.class})
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,property = "__class")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Department.class,name = "department"),
        @JsonSubTypes.Type(value = School.class,name = "school"),
})
public interface OrgNode extends Serializable {

    Integer getId();
    Integer getPid();

    //    @JSONField(name = "childNodes")
    @JsonProperty("childNodes")
    List<OrgNode> obtainChilds();

    //    @JSONField(name = "childNodes")
    @JsonProperty("childNodes")
    void installChilds(List<OrgNode> childs);

    //    @JSONField(serialize = false)
    @JsonIgnore
    default List<Integer> getAllChildIds(){
        final List<Integer> idList = new ArrayList<>();
        idList.add(getId());

        final List<OrgNode> childs = obtainChilds();
        if (childs != null){
            for (OrgNode child : childs) {
                idList.addAll(child.getAllChildIds());
            }
        }
        return idList;
    }

    List<Integer> getSchoolIds();

    static OrgNode dfsFindByIds(Integer id,List<OrgNode> tree){
        if (tree == null || tree.isEmpty()) return null;
        for (OrgNode node : tree) {
            if (id.equals(node.getId())){
                return node;
            }
            final List<OrgNode> orgNodes = node.obtainChilds();
            final OrgNode childFindNode = dfsFindByIds(id, orgNodes);
            if (childFindNode != null) {
                return childFindNode;
            }
        }
        return null;
    }

}
